package me.zingon.self.bigdispatcher.util;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import me.zingon.self.bigdispatcher.exception.ServiceException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author ztc 1423047407@qq.com
 * @version 1.0
 * @date 2020-12-30 11:22
 */
@Component
public class NacosCaller {

    @Value("${spring.cloud.nacos.server-addr}")
    String nacosServer;

    ConcurrentHashMap<String,Integer> routeIndex=new ConcurrentHashMap<>();

    public String getService(String namespaceId,String groupName,String serviceName){
        String api="http://"+nacosServer+"/nacos/v1/ns/instance/list";
        Map<String,Object> params=new HashMap<>(3,1);
        params.put("namespaceId",namespaceId);
        params.put("groupName",groupName);
        params.put("serviceName",serviceName);
        String body = HttpUtil.get(api,params);
        JSONObject result= JSONUtil.parseObj(body);
        JSONArray hosts = result.getJSONArray("hosts");
        if(hosts.size() == 0){
            throw new ServiceException("无可用的service");
        }
        Integer index=0;
        if(routeIndex.containsKey(namespaceId+groupName+serviceName)){
            index=routeIndex.get(namespaceId+groupName+serviceName);
        }
        routeIndex.put(namespaceId+groupName+serviceName,index+1);
        JSONObject host = (JSONObject) hosts.get(index%hosts.size());
        String ip = host.getStr("ip");
        Integer port=host.getInt("port");
        return "http://"+ip+":"+port;
    }

}
